package com.insigma.business.qrcode.soldier.util;

import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;


public class IteratorWrapUtils {

    public static <T> Iterator<T> wrapPageGetApiToIterator(
            Function<Integer, List<T>> pageGetFunc) {

        return new Iterator<T>() {
            private int page = 1;
            private boolean pageGetHasMore = true;
            private Iterator<T> currentIterator = Collections.emptyIterator();

            public void tryStorageGet() {
                if (currentIterator.hasNext()) {
                    return;
                }
                if (!pageGetHasMore) {
                    return;
                }
                List<T> list = pageGetFunc.apply(page);
                pageGetHasMore = !CollectionUtils.isEmpty(list);
                currentIterator = list.iterator();
                page++;
            }

            @Override
            public boolean hasNext() {
                tryStorageGet();
                return currentIterator.hasNext();
            }

            @Override
            public T next() {
                tryStorageGet();
                return currentIterator.next();
            }
        };
    }

}
